﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using eXamineBusiness.SystemDescription.Data;
using eXamineBusiness.SystemDescription.Events;

namespace eXamineBusiness.SystemDescription
{
    public class FailureMode : DescriptionItem
    {
        private readonly ReceivedEventCollection _receivedEvents;
        private ThrownEvent _thrownEvent;

        public FailureMode (String name) : base(name)
        {
            this._receivedEvents = new ReceivedEventCollection();
        }

        public String Effects { get; set; }
        public String Actions { get; set; }
        public ThrownEvent ThrownEvent { get { return this._thrownEvent; } }
        public ReceivedEventCollection ReceivedEvents { get { return this._receivedEvents; } }


        #region Event
        public event EventHandler<DescriptionItemEventArgs> SubItemAdded;
        private void OnSubItemAdd(DescriptionItem item)
        {
            if (this.SubItemAdded != null)
            {
                this.SubItemAdded.Invoke(this, new DescriptionItemEventArgs(item));
            }
        }
        public event EventHandler<DescriptionItemEventArgs> SubItemRemoved;
        private void OnSubItemRemove(DescriptionItem item)
        {
            if (this.SubItemRemoved != null)
            {
                this.SubItemRemoved.Invoke(this, new DescriptionItemEventArgs(item));
            }
        }
        #endregion

        public void Add (ReceivedEvent receivedEvent)
        {
            this.ReceivedEvents.Add(receivedEvent);
            OnSubItemAdd(receivedEvent);
        }

        public void Set (ThrownEvent thrownEvent)
        {
            this._thrownEvent = thrownEvent;
            this.OnSubItemAdd(thrownEvent);
        }


        public bool HasThrownEvent
        {
            get { return this._thrownEvent != null; }
        }

        public void Unset(SystemDescription.ThrownEvent thrownEvent)
        {
            this.OnSubItemRemove(_thrownEvent);
            this._thrownEvent = null;
        }

        public void Remove(ReceivedEvent receivedEvent)
        {
            this.ReceivedEvents.Remove(receivedEvent);
            this.OnSubItemRemove(receivedEvent);
        }

        [Pure]
        public bool Contains(ReceivedEvent receivedEvent)
        {
            if (receivedEvent == null) return false;
            return this._receivedEvents.Contains(receivedEvent);
        }
        [Pure]
        public bool Contains(ThrownEvent receivedEvent)
        {
            if (receivedEvent == null) return false;
            if (!this.HasThrownEvent) return false;
            return this._thrownEvent.Equals(receivedEvent);
        }
    }
}
